//
//  TemplatesListVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/7.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit

typealias TemplateCallback = (XianhuoModel) -> Void

class TemplatesListVC: PublishHistoryVC {

    var isChoosing = false
    var onComplete : TemplateCallback?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "模板列表"
    }
    
    override func getURL() -> String{
        return NetworkManager.XIANHUO_TEMPLATE_LIST
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let selectedModel = self.models[indexPath.row]
        if isChoosing {
            if let callback = onComplete {
                self.navigationController?.popViewController(animated: true)
                callback( selectedModel )
            }
            return
        }
        
        let alert = UIAlertController.init(title: "提示", message: "最多保存5条模板，要删除此模板吗？", preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "删除", style: .default, handler: { (action) in
            self.deleteXH(selectedModel.xianhuoId)
        }))
        
        alert.addAction(UIAlertAction.init(title: "我再想想", style: .cancel, handler: nil))
        self.navigationController?.present(alert, animated: true, completion: nil)
    }
    
    func deleteXH(_ xhId : String) {
        
        _ = NetworkManager.GET(NetworkManager.XIANHUO_TEMPLATE_DELETE,params:["id":xhId]) { (status, response) in
            self.mTableView.endRefreshing(at: .top)
            
            if(status){
                
                DispatchQueue.main.async {
                    self.navigationController?.view.makeToast("成功删除！")
                    self.refresh()
                }
            }
        }
    }
    
    override func emptyHint() ->String {
        return "您还没有保存模板哦～"
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:XianhuoListCell = super.tableView(tableView, cellForRowAt: indexPath) as! XianhuoListCell
        let xianhuo = self.models[indexPath.row]
        cell.locationImg.isHidden = false
        cell.locationTV.text = xianhuo.place
        cell.locationTV.textColor = Const.WTM_GRAY
        return cell
        
    }
}
